package com.business.service.system;

import javax.servlet.http.HttpServletRequest;

import com.business.bean.system.UserBean;

import net.sf.rose.jdbc.PageBean;
import net.sf.rose.jdbc.dao.BeanDAO;
import net.sf.rose.jdbc.query.BeanSQL;
import net.sf.rose.jdbc.service.Service;
import net.sf.rose.util.DateFormat;
import net.sf.rose.web.util.WebUtils;

public class UserService {

    /**
     * 根据用户数据获取用户的全部信息
     * 
     * @param service
     * @param bean
     * @return
     */
    public UserBean get(Service service, UserBean bean) {
        BeanDAO dao = new BeanDAO(service);
        BeanSQL query = dao.getQuerySQL();
        query.setEntityClass(UserBean.class);
        query.createSql(bean);
        return dao.get();
    }

    public PageBean login(HttpServletRequest request, Service service, UserBean bean) {
        PageBean page = new PageBean();
        BeanDAO dao = new BeanDAO(service);
        BeanSQL query = dao.getQuerySQL();
        query.setEntityClass(UserBean.class);
        query.createSql(bean);
        bean = dao.get();
        if (bean == null) {
            page.setSuccess(false);
            page.setMessage("根据用户信息没有找到用户数据!");
            return page;
        }
        // 登录成功，添加该用户到session
        String token = WebUtils.setUserBeanCache(request, bean);
        page.getDataMap().put("_token", token);
        page.setData(bean);
        // 增加登录次数，记录最新登录时间
        UserBean u = new UserBean();
        u.setUserID(bean.getUserID());
        u.setLoginCount(bean.getLoginCount() + 1);
        u.setLastLoginTime(DateFormat.getTimestamp());
        query.createUpdateSql(u);
        dao.update();
        return page;
    }
}